import * as React from 'react';
import { useState } from 'react'
import classNames from 'classnames';

interface PanelProps {
	children?: React.ReactNode;
	className?: string;

	header?: string;
	keya?: string;
	key?: React.Key;
	showArrow?: boolean

	activearr?: Array<string>;
	clickitemfn?: (index:string, flag:boolean) => void;
}

const Panel: React.FC<PanelProps> = props => {
	const prefixCls = 'bh-collapse-item';
	const {
		children,
		className,

		header,
		keya = '',
		key,
		showArrow = true,

		activearr = [],
		clickitemfn,

		...restProps
	} = props;
	let firstKeyActive = activearr.includes(keya);
	const [activeFlag, setactiveFlag] = useState(firstKeyActive);
	const classString = classNames(
		prefixCls,
		className,
		{
			[`${prefixCls}-active`]: activeFlag,
		}
	);

	const onClickCallback = () => {
		let newFlag = !activeFlag;
		setactiveFlag(newFlag);
		clickitemfn && clickitemfn(keya, newFlag);
	};

	return (
		<div {...restProps} className={classString} key={header}>
		    <div className="bh-collapse-header" onClick={onClickCallback}>
		    	{showArrow && (<div>
		    	    <span className="bh-collapse-arrow"><i className="bh-icon bh-icon-arrow-right"></i></span>
		    	</div>)}
		    	{header}
		    </div>
		    <div className="bh-collapse-content">
		    	<div className="bh-collapse-content-box">{children}</div>
		    </div>
		</div>
	)
};


export interface CollapseProps {
	children?: React.ReactNode;
	className?: string;

	defaultActiveKey?: Array<string>;
}

interface CollapsePropsType extends React.FC<CollapseProps> {
	Panel: typeof Panel;
}



const Collapse: CollapsePropsType = props => {
	const prefixCls = 'bh-collapse';
	const {
		children,
		className,

		defaultActiveKey,

		...restProps
	} = props;
	const [activearr, setActivearr] = useState(defaultActiveKey);
	const classString = classNames(
		prefixCls,
		className,
	);
	const getNewListArr = (arr:Array<string>, val:string, flag:boolean) => {
		let index = arr.indexOf(val); 
		if (index > -1) {
			arr.splice(index, 1); 
		}else {
			arr.push(val);
		}
		return arr;
	}
	const clickitemfn = (index:string, flag:boolean) => {
		console.log(index, flag);
		//setActivearr(getNewListArr(activearr, index, flag));
	}

	const getItems = () => {
		const { children } = props;
		const childNodes = Array.prototype.slice.call(children);

		return childNodes.map((child: React.ReactElement, index: number) => {
			const key = child.key || String(index);
			const childProps: PanelProps & { 
				key: React.Key,
			} = {
				...child.props,
				key,
				activearr: activearr,
				clickitemfn: clickitemfn,
			};
			console.log(childProps);
			return React.cloneElement(child, childProps);
		});
	};

	return (
		<div {...restProps} className={classString}>
		    {getItems()}
		</div>
	)
};

Collapse.Panel = Panel;

export default Collapse;